package com.york.tinyrpc.protoss.loadbalancer;

import com.york.tinyrpc.protoss.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 静态加权随机模式
 * 【静态】是因为权重信息是静态的，根据注册时指定
 * 根据服务器的权重随机选择一个服务器处理请求，适用于服务器性能不均的情况
 */
public class StaticWeightedRandomLoadBalancer implements LoadBalancer {

    /**
     * 随机值
     */
    private final Random random = new Random();

    /**
     * 获取目标服务
     *
     * @param requestParams 请求参数
     * @param serviceList   可选服务列表
     * @return
     */
    @Override
    public ServiceMetaInfo getTargetService(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceList) {
        if (serviceList.isEmpty()) return null;

        // 动态计算总权重
        int totalWeight = serviceList.stream()
                .mapToInt(ServiceMetaInfo::getServiceWeight)
                .sum();

        // 生成随机权重值
        int randomWeight = random.nextInt(totalWeight) + 1;

        // 线性遍历寻找目标节点（每次调用重新计算）
        int accumulated = 0;
        for (ServiceMetaInfo instance : serviceList) {
            accumulated += instance.getServiceWeight();
            if (randomWeight <= accumulated) {
                return instance;
            }
        }
        return serviceList.get(0);
    }
}
